<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, nextTick, PropType, ref } from 'vue'
import useSchema from './hooks/useSchema'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { CurdData } from '@/api/supplier/types'
import { Dialog } from '@/components/Dialog'
import { preViewDialogStore } from '@/store/modules/preViewDialog'
import { useI18n } from '@/hooks/web/useI18n'
import { getSelectListApi } from '@/api/operator'
import { getSelectEnumApi } from '@/api/warehouse'

defineOptions({
  name: 'BrandtSave'
})

const { t } = useI18n()
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})
const supplierPreViewId = 'supplierPreView'
const supplierPreViewIdStore = preViewDialogStore(supplierPreViewId)

const operatorList = ref([])
const countryList = ref([])

const getOperatorList = async () => {
  const res = await getSelectListApi({})
  if (res) {
    operatorList.value = res.data.list
  }
}
const getSelectEnumList = async () => {
  const res = await getSelectEnumApi()
  countryList.value = res.data.country
}
getSelectEnumList()
getOperatorList()

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const uploadList = reactive<string[]>([]) // 图片列表

const { crudSchemas } = useSchema(undefined, operatorList, countryList)
const { allSchemas } = useCrudSchemas(crudSchemas)

const rules: FormRules = reactive({})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    setValues({
      image: uploadList.join(',')
    })
    const formData = await getFormData()

    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    await nextTick()
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Dialog
    v-model="supplierPreViewIdStore.isPreViewVisible"
    :title="t('imageViewerDemo.imageViewer')"
    width="50%"
  >
    <img class="w-full" :src="supplierPreViewIdStore.src" alt="Preview Image" />
  </Dialog>

  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
